package com.njrsrc.android.app;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.njrsrc.R;
import com.njrsrc.android.adapters.CompanyPositionListAdapter;
import com.njrsrc.android.bean.CompanyDetails;
import com.njrsrc.android.bean.JobInfo;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.android.library.vpi.BaseSampleActivity;
import com.njrsrc.android.tasks.CompanyDetailTask;
import com.njrsrc.android.tasks.CompanyPositionTask;
import com.njrsrc.android.views.TitleBar;
import com.njrsrc.common.url.RequestUrlProvider;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class CompanyPositionActivity extends BaseSampleActivity implements OnClickListener {
	private TitleBar mBar;
	private FrameLayout companyContainer;
	private ImageView bgImageView;
	private ImageView companyProfile;
	private ImageView companyPositionImg;
	private ImageView companyPositionBg;
	private ViewGroup companyPositionHeader;
	/** 公司职位 */
	private ViewGroup companyPosition;
	/** 公司详情 */
	private ViewGroup companyIntro;
	private ScrollView profileScrollView;
	private TextView name;
	private TextView nature;
	private TextView industry;
	private TextView intro;
	private TextView size;
	private TextView contact;
	private TextView phone;
	private TextView fax;
	private TextView email;
	private TextView url;
	private TextView address;
	private UserInfo userInfo;
	private ProgressDialog progressDialog;
	private ListView jobListView;
	private CompanyPositionListAdapter adapter;
	private int PAGE_ID = 1;
	/** 每页显示的条数 */
	private static final int COUNT = 10;
	private boolean loadingEnd = false;
	private ArrayList<JobInfo> jobList;
	private String requestUrl;
	private String companyId;
	private CompanyDetails companyDetail;
	
	private int screenWeight;
	private int screenHeight;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MsgID.COMPANY_POSITION_QUERY_ERROR:
				Helpers.closeProgressDialog(progressDialog);
				Toast.makeText(CompanyPositionActivity.this, getResources().getString(R.string.connectError),
						Toast.LENGTH_SHORT).show();
				break;
			case MsgID.COMPANY_POSITION_QUERY_FAIL:
				Helpers.closeProgressDialog(progressDialog);
				break;
			case MsgID.COMPANY_POSITION_QUERY_SUCCESS:
				Helpers.closeProgressDialog(progressDialog);
				adapter.setData(jobList);
				adapter.notifyDataSetChanged();
//				jobListView.setSelectionFromTop(1, 400);
				clear();
				break;
			case MsgID.COMPANY_PROFILE_QUERY_ERROR:
				Toast.makeText(CompanyPositionActivity.this, getResources().getString(R.string.connectError),
						Toast.LENGTH_SHORT).show();
				break;
			case MsgID.COMPANY_PROFILE_QUERY_FAIL:
				break;
			case MsgID.COMPANY_PROFILE_QUERY_SUCCESS:
				downloadPic();
				if(!isNull(companyDetail.getName()))
				{
					name.setText(companyDetail.getName());
				}else
				{
					name.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getNature()))
				{
					nature.setText(companyDetail.getNature());
				}else
				{
					nature.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getIndustry()))
				{
					industry.setText(companyDetail.getIndustry());
				}else
				{
					industry.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getIntro()))
				{
					intro.setText(companyDetail.getIntro());
				}else
				{
					intro.setVisibility(View.GONE);
					((View)intro.getParent()).setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getSize()))
				{
					size.setText("规模：" + companyDetail.getSize());
				}else
				{
					size.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getContact()))
				{
					contact.setText("联系人：" + companyDetail.getContact());
				}else
				{
					contact.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getPhone()))
				{
					phone.setText("电话：" + companyDetail.getPhone());
				}else
				{
					phone.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getFax()))
				{
					fax.setText("传真：" + companyDetail.getFax());
				}else
				{
					fax.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getEmail()))
				{
					email.setText("E-Mail：" + companyDetail.getEmail());
				}else
				{
					email.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getUrl()))
				{
					url.setText("网址：" + companyDetail.getUrl());
				}else
				{
					url.setVisibility(View.GONE);
				}
				
				if(!isNull(companyDetail.getAddress()))
				{
					address.setText("地址：" + companyDetail.getAddress());
				}else
				{
					address.setVisibility(View.GONE);
				}
				
				
				if(isNull(companyDetail.getName()) 
						&& isNull(companyDetail.getNature()) 
						&& isNull(companyDetail.getIndustry()))
				{
					((View)name.getParent()).setVisibility(View.GONE);
				}
				
				if(isNull(companyDetail.getSize()) 
						&& isNull(companyDetail.getContact())
						&& isNull(companyDetail.getPhone())
						&& isNull(companyDetail.getFax())
						&& isNull(companyDetail.getEmail())
						&& isNull(companyDetail.getUrl())
						&& isNull(companyDetail.getAddress())						
						)
				{
					((View)address.getParent()).setVisibility(View.GONE);
				}
				
				
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	private Handler mHandler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MsgID.HEAD_DOWNLOAD_SUCCESS) {
				String fileName = (String) msg.obj;
				SoftReference<Bitmap> bitmap = new SoftReference<Bitmap>(
						Helpers.scaleBitmap(fileName, screenWeight, (int)(screenHeight * 0.35)));
				final Drawable mDrawable = new BitmapDrawable(bitmap.get());
				bgImageView.setBackgroundDrawable(mDrawable);
				companyPositionBg.setBackgroundDrawable(mDrawable);
			}
			super.handleMessage(msg);
		}
	};

	private Handler mHandler3 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MsgID.HEAD_DOWNLOAD_SUCCESS) {
				String fileName = (String) msg.obj;
				SoftReference<Bitmap> bitmap = new SoftReference<Bitmap>(
						Helpers.scaleBitmap(fileName, 80, 80));
				final Drawable mDrawable = new BitmapDrawable(bitmap.get());
				companyProfile.setBackgroundDrawable(mDrawable);
				companyPositionImg.setBackgroundDrawable(mDrawable);
				
			}
			super.handleMessage(msg);
		}
	};

	private void downloadPic() {
		if (companyDetail.getLogo_url() != null && !companyDetail.getLogo_url().equals("")) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					Helpers.downloadFile(CompanyPositionActivity.this, companyDetail.getLogo_url(), mHandler2);
				}
			}).start();
		}
		if (companyDetail.getCover_url() != null && !companyDetail.getCover_url().equals("")) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					Helpers.downloadFile(CompanyPositionActivity.this, companyDetail.getCover_url(), mHandler3);
				}
			}).start();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_companyposition);
		DisplayMetrics dm = new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(dm);
	    screenWeight = dm.widthPixels;    //得到宽度
	    screenHeight = dm.heightPixels;  //得到高度
		Bundle data = getIntent().getExtras();
		companyId = data.getString("companyId");
		initView();
		initData();
		initCompanyDetailData();
	}

	private void initView() {
		mBar = (TitleBar) findViewById(R.id.activity_title_bar);
		mBar.setTitleText("公司详情");
		mBar.back.setOnClickListener(this);

		companyContainer = (FrameLayout) findViewById(R.id.companyContainer);

		companyPosition = (ViewGroup) View.inflate(this, R.layout.company_position, null);
		companyPositionHeader = (ViewGroup) View.inflate(this, R.layout.companyposition_header, null);
		bgImageView = (ImageView) companyPositionHeader.findViewById(R.id.companyImg);
		companyProfile = (ImageView) companyPositionHeader.findViewById(R.id.companyProfile);
		companyProfile.setOnClickListener(this);
		jobListView = (ListView) companyPosition.findViewById(R.id.job_listView);
		jobListView.addHeaderView(companyPositionHeader);
		
		jobListView.setOnScrollListener(new OnScrollListener() {
	  		public void onScrollStateChanged(AbsListView view, int scrollState) {
//	  		  下面的注释去掉就有滑动分页功能了。。。
	  			int pos=view.getLastVisiblePosition()+1;
	            switch (scrollState) {
	  			   case OnScrollListener.SCROLL_STATE_IDLE://listview处于静止
	  				   		if(pos >= adapter.getCount() && !loadingEnd)
	  				   		{
	  				   			initData();
	  				   		}
	  				   break;
	  		  	}
	  		}
	  		
	  		public void onScroll(AbsListView view, int firstVisibleItem,
	  				int visibleItemCount, int totalItemCount) {
	  		}
	  	});

		companyIntro = (ViewGroup) View.inflate(this, R.layout.company_profile, null);
		companyPositionBg = (ImageView) companyIntro.findViewById(R.id.companyImg);
		companyPositionImg = (ImageView) companyIntro.findViewById(R.id.companyPosition);
		companyPositionImg.setOnClickListener(this);
		
		profileScrollView = (ScrollView) companyIntro.findViewById(R.id.profileScrollView);
		name = (TextView) companyIntro.findViewById(R.id.name);
		nature = (TextView) companyIntro.findViewById(R.id.nature);
		industry = (TextView) companyIntro.findViewById(R.id.industry);
		intro = (TextView) companyIntro.findViewById(R.id.intro);
		size = (TextView) companyIntro.findViewById(R.id.size);
		contact = (TextView) companyIntro.findViewById(R.id.contact);
		phone = (TextView) companyIntro.findViewById(R.id.phone);
		fax = (TextView) companyIntro.findViewById(R.id.fax);
		email = (TextView) companyIntro.findViewById(R.id.email);
		url = (TextView) companyIntro.findViewById(R.id.url);
		address = (TextView) companyIntro.findViewById(R.id.address);


		adapter = new CompanyPositionListAdapter(this);
		jobListView.setAdapter(adapter);

		companyContainer.addView(companyIntro);
	}

	private void initData() {
		progressDialog = Helpers.showProgressDialog(CompanyPositionActivity.this, R.string.loading);
		requestUrl = RequestUrlProvider.COMPANY_JOB_LIST;
		List<String> params = new ArrayList<String>();
		params.add(AppApplication.mToken);
		params.add(AppApplication.mUserID);
		params.add(companyId);
		params.add("0");
		params.add(PAGE_ID + "");
		params.add(COUNT + "");
		String url = Helpers.combinaStr(requestUrl, params);
		userInfo = new UserInfo();
		jobList = new ArrayList<JobInfo>();
		Object[] args = new Object[4];
		args[0] = mHandler;
		args[1] = url;
		args[2] = userInfo;
		args[3] = jobList;
		new CompanyPositionTask().execute(args);
	}

	private void initCompanyDetailData() {
		requestUrl = RequestUrlProvider.COMPANY_SHOW;
		List<String> params = new ArrayList<String>();
		params.add(companyId);
		params.add(AppApplication.mToken);
		params.add(AppApplication.mUserID);
		String url = Helpers.combinaStr(requestUrl, params);
		userInfo = new UserInfo();
		companyDetail = new CompanyDetails();
		Object[] args = new Object[4];
		args[0] = mHandler;
		args[1] = url;
		args[2] = userInfo;
		args[3] = companyDetail;
		new CompanyDetailTask().execute(args);
	}

	private void clear() {
		if (jobList == null || jobList.size() == 0 || jobList.size() < COUNT) {
			loadingEnd = true;
		} else {
			PAGE_ID++;
		}
		if(jobList != null)
		{
			jobList.clear();
			jobList = null;
		}
		
	}
	
	private boolean isNull(String text)
	{
		if(text != null && text.trim().length() != 0 && !"null".equals(text))
		{
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tb_ibtn_back:
			finish();
			break;
		case R.id.companyProfile:
			companyContainer.removeAllViews();
			companyContainer.addView(companyIntro);
			mBar.setTitleText("公司详情");
			break;

		case R.id.companyPosition:
			companyContainer.removeAllViews();
			companyContainer.addView(companyPosition);
			mBar.setTitleText("公司职位");
			break;
		default:
			break;
		}
	}

}
